//
//  ConsultationHeaderView.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/1/31.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import TYAttributedLabel

protocol ConsultationHeaderViewDelegate: NSObjectProtocol {
    func reloadSuperTableView(view: ConsultationHeaderView)
    
    func updateAttention(isAttention:Bool)
}

class ConsultationHeaderView: UIView, UIWebViewDelegate, BottomShadow, AddCornerUIRectCorner {
    
    @IBOutlet weak var userButtomView: UIView!
    @IBOutlet weak var headerImage: UIImageView!
    @IBOutlet weak var titleLabel: TYAttributedLabel!
    @IBOutlet weak var tagViewHeight: NSLayoutConstraint!
    @IBOutlet weak var titleLabelHeight: NSLayoutConstraint!
    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var webViewHeight: NSLayoutConstraint!
    @IBOutlet weak var headerImageViewHeight: NSLayoutConstraint!
    @IBOutlet weak var tagView: TagScrollView!
    @IBOutlet weak var userContentView: UIView!
    @IBOutlet weak var userInfoHeight: NSLayoutConstraint!
    @IBOutlet weak var userHeaderBGImageView: UIImageView!
    @IBOutlet weak var bottomView: UIView!
    @IBOutlet weak var userAvatarImageView: UIImageView!
    @IBOutlet weak var userName: UILabel!
    @IBOutlet weak var userLevelLabel: UILabel!
    @IBOutlet weak var percentageLabel: UILabel!
    @IBOutlet weak var userConstellationLabel: UILabel!
    @IBOutlet weak var itemsCollectionView: RecommendCollectionView!
    @IBOutlet var slashLines: [UIView]!
    @IBOutlet weak var followButton: UIButton!
    @IBOutlet weak var commentCountView: UIView!
    @IBOutlet weak var commentCountLabel: UILabel!
    weak var delegate: ConsultationHeaderViewDelegate?
    var delegateVc: UIViewController?
    /// 通过xib获取当前View
    @IBOutlet weak var we: UILabel!
    ///
    /// - Returns: self
    static func instanceConsultationHeaderView() -> ConsultationHeaderView {
        let array = Bundle.main.loadNibNamed("\(ConsultationHeaderView.self)", owner: self, options: nil)
        let view = array?.first as! ConsultationHeaderView
        return view
    }
    
    override func awakeFromNib() {
        setUI()
    }
    
    private func setUI() {
        userInfoHeight.constant = kHeight(r: userInfoHeight.constant)
        headerImageViewHeight.constant = kHeight(r: headerImageViewHeight.constant)
        webView.delegate = self
        webView.scrollView.isScrollEnabled = false
        let type:String = UIDevice.current.model
        if type == "iPad" {
            userHeaderBGImageView.isHidden = true
        }
        for line in slashLines {
            line.transform = CGAffineTransform(rotationAngle: DEGREES_TO_RADIANS(x: -70))
        }
        followButton.layer.cornerRadius = followButton.height / 2
        followButton.layer.borderColor = UIColor.lightGray.cgColor
        followButton.layer.borderWidth = 2.0
        bottomView.layoutIfNeeded()
        MyConfigTool.setBlurImage(userHeaderBGImageView, alphaValue: 0.8)
        setSize(isLoad: false)
        
//        addCornerWithView(aView: self.commentCountView, aCorners: [.topLeft,.topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        we.font = UIFont.systemFont(ofSize: 13)
        we.textColor = UIColor.gray
        titleLabel.numberOfLines = 0
        
        let one:String = "一"
        let width = one.sizeOfString(usingFont: titleLabel.font)

        let spacing:CGFloat = ((ScreenWidth - 20) - (width * 17))/16
        
        titleLabel.characterSpacing = unichar(spacing)
        
        
        //        let rect = webView.frame
        //        webView.frame = CGRect(x: 0, y: rect.origin.y, width: ScreenWidth, height: 500)
        //        webView.updateConstraints()
        
        
        //        showRightButtons()
    }
    func setData(model: ArticleModel) {
        
        if model.author?.type == "internal" {
            userContentView.isHidden = true
            userInfoHeight.constant = 0
        }
        
        if let count = model.coverImgPath?.count, count > 0 {
            let path:String = "\(BaseURL)\(model.coverImgPath!)"
            
            
            let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
            headerImage.sd_setImage(with: url! as URL, completed: nil)
            userHeaderBGImageView.sd_setImage(with: url! as URL, completed: nil)

        }
        
        //        headerImage.kf.setImage(with: nil, placeholder: UIImage(named: model.pageUrl))
        if model.title != nil {
           titleLabel.text = model.title!
        }
        
        titleLabel.linesSpacing = 2
        titleLabel.lineBreakMode = CTLineBreakMode.byCharWrapping
        let titleLabelHeight =  titleLabel.getHeightWithWidth(ScreenWidth - 20)
        self.titleLabelHeight.constant = CGFloat(titleLabelHeight)
        
        if let count = model.publishTime?.count, count > 0 {
            let dformatter = DateFormatter()
            
            dformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            
            let date = dformatter.date(from: model.publishTime!)
            
            dformatter.dateFormat = "yyyy-MM-dd"
            self.we.text = dformatter.string(from: date!)
        }
        
        
        if let labels = model.labels{
            var labelstr :[String] = []
            for  object in labels{
                labelstr.append(object.name!)
                
            }
            tagView.showData(titles: labelstr, labelColor: ONColor.subTextColor, fontSize: 10) { tag in
                
            }
        }
        if let headicon = model.author?.headIcon {
            let headPath:String = "\(BaseURL)\(headicon )"
            let headurl = URL(string: headPath)!
            userAvatarImageView.sd_setImage(with: headurl as URL, completed: nil)
            userHeaderBGImageView.sd_setImage(with: headurl as URL, completed: nil)

        }

        if let username = model.author?.nickname{
            userName.text = username
        }
        if let level = model.author?.grade?.gradeCode{
            userLevelLabel.text = level
        }
        if let match = model.author?.matchDegree{
            percentageLabel.text = match
        }
        if let constellation = model.author?.constellation{
            userConstellationLabel.text = constellation
        }
        
        if model.author?.concernType! == "1"{
            self.followButton.isSelected = true
        }else {
            self.followButton.isSelected = false
        }
        
        
        //        userHeaderBGImageView.image = UIImage(named: model.userInfoModel.haderUrl)
        //        userAvatarImageView.image = UIImage(named: model.userInfoModel.haderUrl)
        //        userLevelLabel.text = "\(model.userInfoModel.level)"
        //        userName.text = model.userInfoModel.name
        //        userConstellationLabel.text =  model.userInfoModel.constellation
        setUserContent()
        itemsCollectionView.contentOffset = .zero
        itemsCollectionView.delegateVc = self.delegateVc
//        self.webView.scrollView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
        
        if let content = model.contentUrl {
            let weburl:String = "\(BaseURL)\(model.contentUrl!)"
            self.webView.delegate = self
            let request = URLRequest(url: URL(string: weburl)!)
            
            self.webView.loadRequest(request)
        }
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 0.1) {
            DispatchQueue.main.async {
                let size = self.webView.sizeThatFits(.zero)
                self.webViewHeight.constant = size.height
                self.setSize(isLoad: true)
                self.layoutIfNeeded()
                self.delegate?.reloadSuperTableView(view: self)
            }
        }
        
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        let size = self.webView.sizeThatFits(.zero)
        webViewHeight.constant = size.height
        setSize(isLoad: true)
        self.layoutIfNeeded()
        self.delegate?.reloadSuperTableView(view: self)
    }
    
    
    func scrollViewKVOremove() -> Void {
//        self.webView.scrollView.removeObserver(self, forKeyPath: "contentSize")
    }
    func updateItemsCollectionView(arr:[SearchRecommendModel]) -> Void {
        itemsCollectionView.setData(arr: arr)
    }
    func updateCommentTotalCount(count:Int) -> Void {
        commentCountLabel.text = "(" + String(count) + ")"
    }
    func updateAttentionState(attention:Bool) -> Void {
        followButton.isSelected = attention
    }

//    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//        if keyPath == "contentSize" {
//            let size = self.webView .sizeThatFits(.zero)
//            webViewHeight.constant = size.height
//            setSize(isLoad: true)
//            self.layoutIfNeeded()
//            self.delegate?.reloadSuperTableView(view: self)
//        }
//    }
    
    func setUserContent() {
        setShadow(view: userContentView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        addCornerWithView(aView: userHeaderBGImageView, aCorners: [.topLeft,.topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        addCornerWithView(aView: userButtomView, aCorners: [.bottomLeft,.bottomRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
    }
    @IBAction func attentionAction(_ sender: UIButton) {
        
        guard MineInfoModel.share.hasLoginIn() else {
            let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
            if let dele = self.delegate as? UIViewController {
                dele.navigationController?.pushViewController(loginVC, animated: true)
            }
            return
        }
        self.delegate?.updateAttention(isAttention: sender.isSelected)
    }
}

extension ConsultationHeaderView {
    func setSize(isLoad: Bool) {
        let offset: CGFloat = isLoad ? -1 : 22
        self.height = headerImageViewHeight.constant + 9 +  self.titleLabelHeight.constant + 9 + webViewHeight.constant + tagViewHeight.constant + bottomView.height + offset
    }
    
    
}
